package com.nononsenseapps.feeder.ui.tag

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.PopupMenu
import android.widget.TextView
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gitee.wsl.struct.category.CategoryItemHelper
import com.gitee.wsl.struct.category.CategoryItemWarp
import com.gitee.wsl.struct.category.I_CategoryItem
import com.gitee.wsl.store.StateSavedVar
import com.gitee.wsl.jvm.store.mmkv.MMKVStoreServer
import com.gitee.wsl.struct.tree.bean.TreeNodeItem
import com.kongzue.stacklabelview.StackLabel
import com.kongzue.stacklabelview.interfaces.OnLabelClickListener
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.interfaces.OnInputConfirmListener
import com.nononsenseapps.feeder.db.FEED_ITEM_TAG_ROOT_NAME
import com.nononsenseapps.feeder.db.UIState.GLOBAL.LAST_OPEN_TAG_TREE_NAME
import com.nononsenseapps.feeder.db.entity.FeedItemTag
import com.nononsenseapps.feeder.model.GlobalViewModel
import com.nononsenseapps.feeder.model.category.FeedItemCategoryHelper
import com.nononsenseapps.feeder.ui.R
import com.nononsenseapps.feeder.ui.common.xpopup.ConfirmPopupViewItem
import com.nononsenseapps.feeder.ui.common.xpopup.ConfirmPopupViewItemCallBack
import com.nononsenseapps.feeder.ui.common.xpopup.OnConfirmListener
import com.nononsenseapps.feeder.ui.common.xpopup.XPopupExt
import com.nononsenseapps.feeder.util.isTrue
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.flowOn
import timber.log.Timber


class ItemTagSelecter(parent: View, itemTagClickCallBack:  ItemTagClickCallBack, private val repository: ItemTagRepository, labelClick: OnLabelClickListener) {

    private var stackLabelViewTags : StackLabel = parent.findViewById(R.id.stackLabelView_all_tag)

    private var feedItemTaglist : RecyclerView = parent.findViewById(R.id.all_feed_item_tag)

    private var tagsTreeTitle:TextView = parent.findViewById(R.id.tags_tree_title)

    private var changeTreeButton:Button = parent.findViewById(R.id.change_tree_by_name)

    private var newTreeByName:Button = parent.findViewById(R.id.add_tree_by_name)

    private  var adapter : ItemTagAdapter = ItemTagAdapter(parent.context,itemTagClickCallBack,repository)

    init{
        stackLabelViewTags.onLabelClickListener = labelClick
        feedItemTaglist.layoutManager=LinearLayoutManager(parent.context)
        feedItemTaglist.adapter=adapter


        repository.contextScope().launch {
            val listItemTags = repository.listItemTags()
            withContext(Dispatchers.Main){
                Timber.d("call in ItemTagsFilterDrawerPopup launch listItemTags item count:%d",listItemTags.size)
                stackLabelViewTags.setLabels(listItemTags)
            }
        }

        changeTreeButton.setOnClickListener { it ->
            XPopupExt.asListConfirm(parent.context,"选择目录树",object:OnConfirmListener<ConfirmPopupViewItem>{
                override fun onConfirm(item: ConfirmPopupViewItem) {
                    if(item.key==FEED_ITEM_TAG_ROOT_NAME){
                        repository.setLoadTreeName(null)
                    }else
                        repository.setLoadTreeName(item.toPair())
                    flushTree()
                }

            },object:ConfirmPopupViewItemCallBack{
                override fun getListItemTitle(item: ConfirmPopupViewItem): String {
                    return item.value
                }

                override fun listItems(): List<ConfirmPopupViewItem> {
                    val treeItemMap = mutableListOf(Pair(FEED_ITEM_TAG_ROOT_NAME,"系统目录树"))
                    treeItemMap.addAll(FeedItemCategoryHelper.saveTagValueMap.toList())
                    return treeItemMap.map { ConfirmPopupViewItem(it.first,it.second) }
                }

                override fun removeItem(item: ConfirmPopupViewItem) {
                    if(item.key==FEED_ITEM_TAG_ROOT_NAME) return
                    FeedItemCategoryHelper.removeCustomTagTree(item.key)
                }

                override fun updateItem(item: ConfirmPopupViewItem) {
                    if(item.key==FEED_ITEM_TAG_ROOT_NAME) return
                    FeedItemCategoryHelper.getTreeItem(item.key)?.let {
                        it.name=item.value
                        FeedItemCategoryHelper.saveTree(item.key)
                    }
                }

                override fun addItem(item: ConfirmPopupViewItem) {
                    FeedItemCategoryHelper.addCustomTagTree(item.value)?.let {treeItem->
                        item.key=treeItem.id
                    }
                }

            }).show()
        }

        newTreeByName.setOnClickListener {
            XPopup.Builder(parent.context).asInputConfirm("新建目录树","请输入目录名称:","","按地区分类"){
                if(repository.insertNewTreeByName(it))
                   flushTree()
            }.show()
        }


        val viewModelVisibility=if(repository.isEditModel()) View.VISIBLE else View.GONE

        changeTreeButton.visibility = viewModelVisibility
        newTreeByName.visibility = viewModelVisibility

        flushTree()
    }

    fun flushTree(){
        repository.contextScope().launch {
            repository.loadDbItemTags().flowOn(Dispatchers.Main).collect { it ->
                Timber.d(
                    "call in ItemTagsFilterDrawerPopup launch loadDbItemTags item count:%d",
                    it.size()
                )
                adapter.submitFeedItemTagList(it)
                tagsTreeTitle.text=repository.getLoadTreeName()?:"系统目录树"
            }
        }
    }
}

interface ItemTagRepository{
    fun listItemTags() : List<String>

    suspend fun findSimileTagWithTag(tag :String ): List<String>

    fun loadDbItemTags(): Flow<CategoryItemWarp>

    fun loadHotDbItemTags(): Flow<List<FeedItemTag>>

    fun updateItemTag(id: Long,tagsList : List<String>)

    fun contextScope():CoroutineScope

    fun setLoadTreeName(treePair: Pair<String, String>?)

    fun getLoadTreeName():String?

    fun updateItemTagHot(itemTag: CategoryItemWarp, hot: Boolean)

    fun delete(itemTag: CategoryItemWarp)

    fun updateByParentName(itemTag: CategoryItemWarp, feedItemTagRootName: String)

    fun insert(name:String,parentTagWarp : CategoryItemWarp)

    fun updateFeedItemTagAttentionLevel(itemTag: CategoryItemWarp, leave: Int)

    fun updateFeedItemTagParentTag(itemTag: CategoryItemWarp, parentTag: CategoryItemWarp)

    fun getItemWarpTitle(itemTagWap: CategoryItemWarp): String

    fun isHot(itemTagWap: CategoryItemWarp): Boolean

    fun getAttentionLevel(itemTagWap: CategoryItemWarp): Int

    fun insertNewTreeByName(it: String):Boolean

    fun isEditModel():Boolean

}

abstract class AdapterItemTagRepository(val globalViewModel: GlobalViewModel):ItemTagRepository{

    var currentTreeEntry: Pair<String, String>?=null

    val feedItemTagDao = globalViewModel.feedItemTagDao

    var currentFlow=MutableSharedFlow<CategoryItemWarp>(1, 1, BufferOverflow.DROP_OLDEST)

    var lastOpenTreeID by StateSavedVar(MMKVStoreServer.get(),LAST_OPEN_TAG_TREE_NAME,FEED_ITEM_TAG_ROOT_NAME)

    init{
        if(lastOpenTreeID != FEED_ITEM_TAG_ROOT_NAME)
            FeedItemCategoryHelper.getTreeItem(lastOpenTreeID)?.let{ currentTreeEntry = it.id to it.name}
        fireDatasChanged()
    }

    override fun listItemTags(): List<String> {
        return emptyList()
    }

    override fun insertNewTreeByName(it: String): Boolean {
        FeedItemCategoryHelper.addCustomTagTree(it)?.let {
            currentTreeEntry= Pair(it.id,it.name)
            fireDatasChanged()
            return true
        }
        return false
    }

    override suspend fun findSimileTagWithTag(tag: String): List<String> {
        return globalViewModel.findSimileTagWithTag(tag)
    }

    override fun loadDbItemTags(): Flow<CategoryItemWarp> {
        return currentFlow
    }

    override fun loadHotDbItemTags(): Flow<List<FeedItemTag>> {
        return globalViewModel.loadHotItemTags()
    }

    override fun updateItemTag(id: Long, tagsList: List<String>) {
        globalViewModel.updateItemTag(id, tagsList)
    }

    override fun setLoadTreeName(treePair: Pair<String, String>?) {
        this.currentTreeEntry = treePair
        this.lastOpenTreeID=treePair?.first?:FEED_ITEM_TAG_ROOT_NAME
        fireDatasChanged()
    }

    private fun fireDatasChanged()= contextScope().launch{
        if(currentTreeEntry!=null){
            val rootTree=FeedItemCategoryHelper.buildTreeCategoryRoot(currentTreeEntry!!.first)
            currentFlow.emit(rootTree)
        } else {
            val rootTag = CategoryItemWarp(com.nononsenseapps.feeder.db.buildFeedItemTagRoot())
            globalViewModel.loadAllItemTags().collect { items ->
                CategoryItemHelper.buildRoot(rootTag, items)
                currentFlow.emit(rootTag)
            }
        }
    }

    override fun getLoadTreeName(): String? {
        return currentTreeEntry?.second
    }

    override fun updateItemTagHot(itemWarp: CategoryItemWarp, hot: Boolean) {
        when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    feedItemTagDao.updateItemTagHot(itemTag.id, hot)
                }
            }
            is TreeNodeItem->{
                itemTag.hot=hot
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }

    }

    override fun delete(itemWarp: CategoryItemWarp) {
        when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    feedItemTagDao.delete(itemTag)
                }
            }
            is TreeNodeItem->{
                val parent=itemWarp.parent() as CategoryItemWarp
                (parent.item as TreeNodeItem).removeNodeItem(itemTag)
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }

    }

    override fun updateByParentName(itemWarp: CategoryItemWarp, feedItemTagRootName: String) {
        when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    feedItemTagDao.updateByParentName(itemTag.name, feedItemTagRootName)
                }
            }
            is TreeNodeItem->{
                val newParent=FeedItemCategoryHelper.getTreeItem(feedItemTagRootName) as TreeNodeItem
                val parent=itemWarp.parent() as CategoryItemWarp
                (parent.item as TreeNodeItem).removeNodeItem(itemTag)
                newParent.addNodeItem(itemTag)
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }
    }

    override fun insert(name:String,parentTagWarp : CategoryItemWarp) {
        when(val itemTag=parentTagWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    val parentTag=parentTagWarp.item as FeedItemTag
                    feedItemTagDao.insert(FeedItemTag(name=name, parentTag = parentTag.name))
                }
            }
            is TreeNodeItem->{
                itemTag.addNodeItem(TreeNodeItem(name))
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }
    }

    override fun updateFeedItemTagAttentionLevel(itemWarp: CategoryItemWarp, leave: Int) {
        when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    globalViewModel.updateFeedItemTagAttentionLevel(itemTag.id,leave)
                }
            }
            is TreeNodeItem->{
                itemTag.attentionLevel=leave
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }
    }

    override fun updateFeedItemTagParentTag(itemWarp: CategoryItemWarp, parentTag: CategoryItemWarp) {
        when(val itemTag= itemWarp.item){
            is FeedItemTag->{
                contextScope().launch(Dispatchers.IO) {
                    val parentItemTag=parentTag.item as FeedItemTag
                    globalViewModel.updateFeedItemTagParentTag(itemTag,parentItemTag.name )
                }
            }
            is TreeNodeItem->{
                val newParentItem=parentTag.item as TreeNodeItem
                val currentItemParent=(itemWarp.parent() as CategoryItemWarp).item as TreeNodeItem

                currentItemParent.removeNodeItem(itemTag)
                newParentItem.addNodeItem(itemTag)
                FeedItemCategoryHelper.saveTree(currentTreeEntry!!.first)
                fireDatasChanged()
            }
        }
    }

    override fun getItemWarpTitle(itemWarp: CategoryItemWarp): String {
        if(itemWarp.isRoot)
            return "未分类"
        return when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                itemTag.name
            }
            is TreeNodeItem->{
                itemTag.name
            }
            else -> {""}
        }
    }

    override fun isHot(itemWarp: CategoryItemWarp): Boolean {
        return when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                itemTag.hot
            }
            is TreeNodeItem->{
                itemTag.hot
            }
            else -> {false}
        }
    }

    override fun getAttentionLevel(itemWarp: CategoryItemWarp): Int {
        return when(val itemTag=itemWarp.item){
            is FeedItemTag->{
                itemTag.attentionLevel
            }
            is TreeNodeItem->{
                itemTag.attentionLevel
            }
            is I_CategoryItem<*>->{
                itemTag.attentionLevel()
            }
            else -> {0}
        }
    }

    override fun isEditModel(): Boolean {
        return true
    }
}

class ViewModelItemTagRepository(private val feedItemTagRepository:ItemTagRepository):ItemTagRepository{

    override fun listItemTags(): List<String> = emptyList()

    override suspend fun findSimileTagWithTag(tag: String): List<String> = emptyList()

    override fun loadDbItemTags(): Flow<CategoryItemWarp> = feedItemTagRepository.loadDbItemTags()

    override fun loadHotDbItemTags(): Flow<List<FeedItemTag>> = feedItemTagRepository.loadHotDbItemTags()

    override fun updateItemTag(id: Long, tagsList: List<String>) {}

    override fun contextScope(): CoroutineScope =feedItemTagRepository.contextScope()

    override fun setLoadTreeName(treePair: Pair<String, String>?) {
        feedItemTagRepository.setLoadTreeName(treePair)
    }

    override fun getLoadTreeName(): String? {
        return feedItemTagRepository.getLoadTreeName()
    }

    override fun updateItemTagHot(
        itemTag: CategoryItemWarp,
        hot: Boolean
    ) {}

    override fun delete(itemTag: CategoryItemWarp) {}

    override fun updateByParentName(
        itemTag: CategoryItemWarp,
        feedItemTagRootName: String
    ) {}

    override fun insert(name:String,parentTagWarp :  CategoryItemWarp) {}

    override fun updateFeedItemTagAttentionLevel(
        itemTag: CategoryItemWarp,
        leave: Int
    ) {}

    override fun updateFeedItemTagParentTag(
        itemTag: CategoryItemWarp,
        parentTag: CategoryItemWarp
    ) {}

    override fun getItemWarpTitle(itemTagWap: CategoryItemWarp): String {
        return feedItemTagRepository.getItemWarpTitle(itemTagWap)
    }

    override fun isHot(itemTagWap: CategoryItemWarp): Boolean {
        return feedItemTagRepository.isHot(itemTagWap)
    }

    override fun getAttentionLevel(itemTagWap: CategoryItemWarp): Int {
        return feedItemTagRepository.getAttentionLevel(itemTagWap)
    }

    override fun insertNewTreeByName(it: String): Boolean {
        return false
    }

    override fun isEditModel(): Boolean {
        return false
    }
}

@InternalCoroutinesApi
@SuppressLint("ViewConstructor")
class ItemTagsFilterDrawerPopup(context: Context, private val itemTagClickCallBack:  ItemTagClickCallBack, private val repository: ItemTagRepository): BottomPopupView(context),
    OnLabelClickListener {

    private lateinit var  stackLabelViewSimilarTag : StackLabel

    private lateinit var stackLabelViewSelectedTag : StackLabel

    private lateinit var itemTagSelecter: ItemTagSelecter

    override fun getImplLayoutId(): Int {
        return R.layout.popup_item_filter_tag
    }

    override fun onClick(index: Int, v: View?, s: String?) {
        if (s != null) {
            itemTagClicked(s)
        }
    }

    override fun onCreate() {
        super.onCreate()
        stackLabelViewSimilarTag=findViewById(R.id.stackLabelView_similar_tag)
        stackLabelViewSimilarTag.onLabelClickListener = this


        stackLabelViewSelectedTag= findViewById(R.id.stackLabelView_selected_tag)
        stackLabelViewSelectedTag.setOnLabelClickListener { index, v, s ->
            stackLabelViewSelectedTag.remove(s)
            refreshTagsToFilter()
        }


        val warpCallBackAdapter=object:ItemTagClickCallBackAdapter(itemTagClickCallBack){
            override fun onItemTagClick(itemTagWap: CategoryItemWarp) {
                super.onItemTagClick(itemTagWap)
                itemTagClicked(repository.getItemWarpTitle(itemTagWap))
            }
        }

        itemTagSelecter=ItemTagSelecter(findViewById(R.id.item_tag_select),warpCallBackAdapter,repository,this)

        this.findViewTreeLifecycleOwner()?.lifecycleScope?.launch {
            repository.loadHotDbItemTags().flowOn(Dispatchers.Main).collect { value ->
                val hotList = value.map { it.name }
                stackLabelViewSimilarTag.setLabels(hotList)
            }
        }

        val viewModelVisibility=if(repository.isEditModel()) View.VISIBLE else View.GONE

        stackLabelViewSimilarTag.visibility=viewModelVisibility
        stackLabelViewSelectedTag.visibility=viewModelVisibility
    }

    fun itemTagClicked(tag:String){
        if(!stackLabelViewSelectedTag.isHave(tag) && stackLabelViewSelectedTag.labels.size < 5) {
            stackLabelViewSelectedTag.addLabel(tag)
            loadDdSimilarTag(tag)
            refreshTagsToFilter()
        }
    }

    private fun refreshTagsToFilter(){
        itemTagClickCallBack.selectedTagsToFilter(stackLabelViewSelectedTag.labels)
    }

    private fun loadDdSimilarTag(tag: String){
        stackLabelViewSimilarTag.setLabels(emptyArray())
        this.findViewTreeLifecycleOwner()?.lifecycleScope?.launch {
            val listItemTags=repository.findSimileTagWithTag(tag)
            withContext(Dispatchers.Main){
                Timber.d("call in ItemTagsFilterDrawerPopup launch loadDdSimilarTag item count:%d",listItemTags.size)
                stackLabelViewSimilarTag.setLabels(listItemTags)
            }
        }
    }

}

@InternalCoroutinesApi
open class ItemTagsEditDrawerPopup(context:Context, val itemTagClickCallBack: ItemTagClickCallBack, val repository: ItemTagRepository, val id:Long, val _itemCurrentTags:List<String>, val itemSampleTags:List<String>, val callBack:(id: Long, itemCurrentTags:List<String>)->Unit):
    CenterPopupView(context),OnLabelClickListener {
    lateinit var stackLabelViewTag: StackLabel
    lateinit var textView_newTag: TextView
    lateinit var buttom_newTag: Button
    lateinit var stackLabelViewSampleTags: StackLabel

    val itemCurrentTags = ArrayList<String>()

    lateinit var itemTagSelecter:ItemTagSelecter

    override fun getImplLayoutId(): Int {
        return R.layout.popup_item_tags
    }

    override fun onCreate() {
        super.onCreate()

        stackLabelViewTag=findViewById(R.id.stackLabelView_tag)
        stackLabelViewTag.setOnLabelClickListener { index, v, s ->
            stackLabelViewTag.remove(index)
            saveTag()
        }

        stackLabelViewSampleTags=findViewById(R.id.stackLabelView_sample_tag)
        stackLabelViewSampleTags.onLabelClickListener = this

        textView_newTag=findViewById(R.id.textView_newTag)
        buttom_newTag=findViewById(R.id.button_add_tag)
        buttom_newTag.setOnClickListener {
            textView_newTag.text?.isNotEmpty().isTrue {
                val s=textView_newTag.text.toString()
                if(!stackLabelViewTag.isHave(s)) {
                    stackLabelViewTag.addLabel(s)
                    saveTag()
                }
            }
        }

        val itemTagClickAdapter=object :ItemTagClickCallBackAdapter(itemTagClickCallBack){
            override fun onItemTagClick(itemTagWap: CategoryItemWarp) {
                super.onItemTagClick(itemTagWap)
                tagClick(repository.getItemWarpTitle(itemTagWap))
            }
        }

        itemTagSelecter=ItemTagSelecter(findViewById(R.id.item_tag_select),itemTagClickAdapter,repository,this)

        itemCurrentTags.clear()
        itemCurrentTags.addAll(_itemCurrentTags)
        stackLabelViewTag.setLabels(itemCurrentTags)

        stackLabelViewSampleTags.setLabels(itemSampleTags)
        stackLabelViewSampleTags.visibility=if(itemSampleTags.isNotEmpty() && repository.isEditModel())  View.VISIBLE else View.GONE

        val editVisibility=if(repository.isEditModel())  View.VISIBLE else View.GONE

        stackLabelViewTag.visibility = editVisibility
        textView_newTag.visibility = editVisibility
        buttom_newTag.visibility = editVisibility

        val itemTagTitleView:TextView=findViewById(R.id.item_tag_pop_title)
        itemTagTitleView.visibility=editVisibility
    }

    private fun saveTag(){
        repository.updateItemTag(id,stackLabelViewTag.labels)
        callBack(id,stackLabelViewTag.labels)
    }

    fun tagClick(tag:String){
        if(!stackLabelViewTag.isHave(tag)) {
            stackLabelViewTag.addLabel(tag)
            saveTag()
        }
    }

    override fun onClick(index: Int, v: View?, s: String?) {
        if (s != null) {
            tagClick(s)
        }
    }

}

@OptIn(InternalCoroutinesApi::class)
 fun showFeedItemTagPopMenu(context: Context, view:View, currentItemTag: CategoryItemWarp, feedItemTagRepository:ItemTagRepository){
    val popupMenu = PopupMenu(context, view)
    var selectTagPop: BasePopupView?=null
    popupMenu.menuInflater.inflate(R.menu.popmenu_item_tag, popupMenu.menu)
    popupMenu.setOnMenuItemClickListener { menuItem ->
        when(menuItem.itemId){
            R.id.action_delete ->{
                if(currentItemTag.subItemList.size>0)
                    feedItemTagRepository.updateByParentName(currentItemTag, FEED_ITEM_TAG_ROOT_NAME)
                feedItemTagRepository.delete(currentItemTag)
            }
            R.id.action_new -> {
                XPopup.Builder(context).asInputConfirm(feedItemTagRepository.getItemWarpTitle(currentItemTag),"",object :
                    OnInputConfirmListener {
                    override fun onConfirm(text: String?) {
                        if(text.isNullOrEmpty()) return
                        /*feedItemTagRepository.contextScope().launch(Dispatchers.IO) {
                            feedItemTagRepository.loadDbItemTags().collect { tags ->
                               val exits = tags.find { feedItemTagRepository.getItemWarpTitle(
                                   it as CategoryItemWarp
                               ) == text }
                               if(exits == null)
                                   feedItemTagRepository.insert(text,itemTagWap)
                            }
                        }*/
                        feedItemTagRepository.insert(text,currentItemTag)
                    }
                }).show()
            }
            R.id.action_mark_hot -> {
                feedItemTagRepository.updateItemTagHot(currentItemTag,true)
                //tag.hot=true
            }
            R.id.action_mark_un_hot ->{
                feedItemTagRepository.updateItemTagHot(currentItemTag,false)
                //tag.hot=false
            }
            R.id.action_select_parent_tag -> {
                selectTagPop = XPopup.Builder(context).asCustom(
                    ItemTagsEditDrawerPopup(
                        context,
                        itemTagClickCallBack = object: AbstractItemTagClickCallBack() {
                            override fun onItemTagClick(itemTag: CategoryItemWarp) {
                                Timber.d("selectTagPop select parent tag onItemTagClick selectTagPop:${selectTagPop==null}")
                                feedItemTagRepository.updateFeedItemTagParentTag(currentItemTag,itemTag)
                                selectTagPop?.dialog?.dismiss()
                                selectTagPop=null
                            }
                        } ,
                        repository = ViewModelItemTagRepository(feedItemTagRepository),
                        id = 0,
                        _itemCurrentTags = emptyList(),
                        itemSampleTags = emptyList(),
                        callBack =  { _,tagStr->
                        }
                    )
                ).show()
            }
            /*R.id.action_expander -> {itemTagWap.showAll = true}
            R.id.action_un_expander -> {itemTagWap.showAll = false}*/
            R.id.action_attention_love_0 -> {
                feedItemTagRepository.updateFeedItemTagAttentionLevel(currentItemTag, 0)
            }
            R.id.action_attention_love_1 -> {
                feedItemTagRepository.updateFeedItemTagAttentionLevel(currentItemTag, 1)
            }
            R.id.action_attention_love_2 -> {
                feedItemTagRepository.updateFeedItemTagAttentionLevel(currentItemTag, 2)
            }
            R.id.action_attention_love_3 -> {
                feedItemTagRepository.updateFeedItemTagAttentionLevel(currentItemTag, 3)
            }
            R.id.action_attention_love_4 -> {
                feedItemTagRepository.updateFeedItemTagAttentionLevel(currentItemTag, 4)
            }
        }
        true
    }

    popupMenu.menu.findItem(R.id.action_new).isVisible = !currentItemTag.isLeaf||currentItemTag.isRoot

    popupMenu.menu.findItem(R.id.action_delete).isVisible = currentItemTag.isLeaf&&!currentItemTag.isRoot

    popupMenu.menu.findItem(R.id.action_select_parent_tag).isVisible = !currentItemTag.isRoot


    val hot = feedItemTagRepository.isHot(currentItemTag)

    popupMenu.menu.findItem(R.id.action_mark_hot).isVisible = !hot&&!currentItemTag.isRoot
    popupMenu.menu.findItem(R.id.action_mark_un_hot).isVisible = hot&&!currentItemTag.isRoot

    popupMenu.menu.findItem(R.id.action_expander).isVisible = false
    popupMenu.menu.findItem(R.id.action_un_expander).isVisible = false
    /*popupMenu.menu.findItem(R.id.action_expander).isVisible = !itemTagWap.isLeaf && !itemTagWap.showAll
    popupMenu.menu.findItem(R.id.action_un_expander).isVisible = !itemTagWap.isLeaf && itemTagWap.showAll*/

    popupMenu.menu.findItem(R.id.action_attention_love).isVisible = !currentItemTag.isRoot

    if(!currentItemTag.isRoot) {
        val attentionLevel = feedItemTagRepository.getAttentionLevel(currentItemTag)

        popupMenu.menu.findItem(R.id.action_attention_love_0).isEnabled =
            attentionLevel != 0 && !currentItemTag.isRoot
        popupMenu.menu.findItem(R.id.action_attention_love_1).isEnabled =
            attentionLevel != 1 && !currentItemTag.isRoot
        popupMenu.menu.findItem(R.id.action_attention_love_2).isEnabled =
            attentionLevel != 2 && !currentItemTag.isRoot
        popupMenu.menu.findItem(R.id.action_attention_love_3).isEnabled =
            attentionLevel != 3 && !currentItemTag.isRoot
        popupMenu.menu.findItem(R.id.action_attention_love_4).isEnabled =
            attentionLevel != 4 && !currentItemTag.isRoot
    }
    popupMenu.show()
}